<?php

namespace app_supplier\controllers;

use Yii;
use app_supplier\models\DealerPurchasingMaterial;
use app_supplier\helpers\PurchaseHelper;
use yii\helpers\Url;
use yii\web\Response;
use yii\helpers\ArrayHelper;

class PurchaseController extends BaseController
{
    public $locationUrl = '';
    /**
     * @return string
     */
    public function actionIndex()
    {
        $this->view->title = '求购需求';
        $this->pageTitle = '求购订单';
        $whereGet = array_merge([
            'cmbProvince'=>'',
            'cmbCity'=>'',
            'cmbArea'=>'',
            'start'=>'',
            'end'=>'',
            'status'=>'',
            'time'=>'all',
            't'=>'all',
        ], Yii::$app->request->get());
        $price_status = Yii::$app->request->get('price_status', 0);
        $wherePost = PurchaseHelper::FilterArguments($whereGet);
        $where = PurchaseHelper::disposeArguments($wherePost);
        $andWhere = PurchaseHelper::disposeAndWhere($wherePost);

        if (empty($wherePost) || isset($wherePost['time']) && $wherePost['time'] =='all') {
            if ($whereGet['t']=='all') {
                $list = PurchaseHelper::getList($this->params, [], [], [], $price_status);
            } else {
                $list = PurchaseHelper::getList($this->params, $where, $andWhere, [], $price_status);
            }
        } else {
            $list = PurchaseHelper::getList($this->params, $where, $andWhere, [], $price_status);
        }
        
        $sortFields = ['material_price', 'demand_time', 'days','material_number' ];#order fields
        
        return $this->render('index', [
            'list'=>$list['list'],
            'page'=>$list['page'],
            'condition'=>$whereGet,
            'sort'=>$this->params['sortField'],
            'order'=>$this->params['order'],
            'price_status'=>$price_status,
            'order_info'=>PurchaseHelper::getOrderState(),
            'sortUrl'=>PurchaseHelper::groupSortUrl($sortFields, $this->locationUrl, $this->params['order'])
        ]);
    }

    /**配件消耗列表
     * @return string
     */
    public function actionOrder()
    {
        $this->view->title = '配件消耗列表';
        $this->pageTitle = '配件消耗';
        $whereParams = ArrayHelper::merge([
            'cmbProvince'=>'',
            'cmbCity'=>'',
            'cmbArea'=>'',
            't'=>'all',
            'time'=>'all',
            'material'=>'',
            'brand'=>'',
            'car_type'=>'',
            'start'=>'',
            'end'=>''
        ], Yii::$app->request->get());

        if ($whereParams['material'] == 'all') {
            $whereFields = ['cmbProvince', 'cmbCity', 'cmbArea'];
        } else {
            $whereFields = ['cmbProvince', 'cmbCity', 'cmbArea', 'material'];
        }

        if ($whereParams['brand'] == 'all') {
            $andWhereFields =  ['time', 'car_type','start', 'end'];
        } else {
            $andWhereFields = ['time','brand', 'car_type','start', 'end'];
        }

        $where = PurchaseHelper::disposeArguments(ArrayHelper::filter($whereParams, $whereFields));

        $andWhere = ArrayHelper::filter($whereParams, $andWhereFields);

        $andWhere = PurchaseHelper::filterTimeAndLike($andWhere);
        if (isset($whereParams['time']) && $whereParams['time']=='all') {
            if ($whereParams['t']=='all') {
                $list = PurchaseHelper::materialExpendList($this->params);
            } else {
                $list = PurchaseHelper::materialExpendList($this->params, $where, $andWhere);
            }
        } else {
            $list = PurchaseHelper::materialExpendList($this->params, $where, $andWhere);
        }

        $sortFields = ['create_time'];
        return $this->render('order',[
            'material'=>PurchaseHelper::material(),
            'brand'=>PurchaseHelper::brand(1),
            'car_type'=>PurchaseHelper::carType(),
            'condition'=>$whereParams,
            'items'=>$list['list'],
            'page'=>$list['page'],
            'sort'=>$this->params['sortField'],
            'order'=>$this->params['order'],
            'sortUrl'=>PurchaseHelper::groupSortUrl($sortFields, $this->locationUrl, $this->params['order'])
        ]);
    }

    /**
     * 获取材料下拉选择
     */
    public function actionBrand($id=0)
    {
        $list = PurchaseHelper::brand($id);

        return $this->returnAjax([
            'status'=>200,
            'msg'=>'success',
            'data'=>$list
        ]);
    }

    /**获取车类型
     * @return array
     */
    public function actionCar_type()
    {
        $parentID = Yii::$app->request->get('pid', 0);
        $latter = Yii::$app->request->get('l', '');

        return $this->returnAjax(PurchaseHelper::getCatType($parentID, $latter));
    }

    /**处理报价
     * @return array
     */
    public function actionDispose()
    {
        $dealer = null;
        $type = Yii::$app->request->get('action');
        $id = Yii::$app->request->get('id');
        $did = Yii::$app->request->get('did');
        $dealer_info = Yii::$app->session->get('user_dealer');
        $dealer_id = $dealer_info['dealer_id'];
        $user_id = Yii::$app->user->id;


        if ($type=='offer') {
            $dealer = DealerPurchasingMaterial::find()
                ->where('d_m_id=:d_m_id and dealer_id=:dealer_id', [':d_m_id'=>$id, ':dealer_id'=>$dealer_id])
                ->one();
            if (!$dealer) {
                $dealer = new DealerPurchasingMaterial();
            }

            $arr = [
                'd_m_id'=>$id,
                'dpd_id'=>$did,
                'dealer_id'=>$dealer_id,
                'user_id'=>$user_id,
                'state'=>0
            ];


            $dealer->attributes = $arr;

            if ($dealer->validate() && $dealer->save()) {
                $ajax = [
                    'status'=>200,
                    'msg'=>'报价成功',
                    'info'=>'我已报价',
                    'data'=>[]
                ];
            } else {
                $ajax = [
                    'status'=>102,
                    'msg'=>'报价失败',
                    'info'=>'',
                    'data'=>[
                        'error'=>[$dealer->getErrors()]
                    ]
                ];
            }
        } else {
            $dealer = DealerPurchasingMaterial::find()
                ->where('d_m_id=:d_m_id and dealer_id=:dealer_id and user_id=:user_id', [':d_m_id'=>$id, ':dealer_id'=>$dealer_id, ":user_id"=>$user_id])
                ->one();
            if (!$dealer) {
                $dealer = new DealerPurchasingMaterial();
            }
            $arr = [
                'd_m_id'=>$id,
                'dpd_id'=>$did,
                'dealer_id'=>$dealer_id,
                'user_id'=>$user_id,
                'state'=>1
            ];
            $dealer->attributes = $arr;

            if ($dealer->save()) {
                $ajax = [
                    'status'=>200,
                    'msg'=>'取消报价成功',
                    'info'=>'点击查看',
                    'data'=>[]
                ];
            } else {
                $ajax = [
                    'status'=>102,
                    'msg'=>'取消报价失败',
                    'info'=>'',
                    'data'=>[
                        'error'=>[$dealer->getErrors()]
                    ]
                ];
            }
        }

        return $this->returnAjax($ajax);
    }

    /**预处理参数
     * @param
     * @return bool
     */
    public function beforeAction($action)
    {
        $this->locationUrl = Yii::$app->request->url;
        return parent::beforeAction($action);
    }


}
